package com.baozhun.mall.common.util

import com.baozhun.mall.common.R
import com.baozhun.mall.common.base.mAppViewModel
import com.baozhun.mall.common.model.bean.UserInfo
import com.baozhun.mall.common.model.request.UpdateUserInfoReqBean
import com.baozhun.mall.common.network.mCommonApiService
import com.baozhun.mall.common.util.eventbus.EventBusUtils
import com.baozhun.mall.common.util.eventbus.EventCode
import com.blankj.utilcode.util.SPUtils
import com.blankj.utilcode.util.ToastUtils
import me.hgj.jetpackmvvm.ext.request
import java.io.File

/**
 * @Title：登陆帮助类
 * @Description：
 * @Author：xuefeng.zhu
 * @Since：2023/2/12
 * @Version：1.0.0
 */
class LoginHelper {

    companion object {
        fun getInstance() = InstanceHelper.sSingle
    }

    object InstanceHelper {
        val sSingle = LoginHelper()
    }

    /**
     * 登陆成功后的逻辑处理
     */
    fun loginSuccess(userInfo: UserInfo?, loginSuccess: () -> Unit) {
        ToastUtils.showShort(com.baozhun.mall.res.R.string.login_success)
        //更新token
        CacheUtil.setUser(userInfo, false)
        mAppViewModel.request({ mCommonApiService.getUserInfo() }, {
            //更新其它信息
            CacheUtil.setUser(it, setAlias = true)
            checkPersonalizationSet()
            EventBusUtils.sendEvent(EventCode.LOGIN_SUCCESS)
            loginSuccess.invoke()
        }, showErrorMsg = false)
    }

    /**
     * 检查个性化设置
     */
    private fun checkPersonalizationSet() {
        var chooseSex = SPUtils.getInstance().getInt(Constants.SPKey.CHOOSE_SEX)
        //只处理一次
        SPUtils.getInstance().put(Constants.SPKey.CHOOSE_SEX, -1)
        if (chooseSex != -1) {
            mAppViewModel.request({ mCommonApiService.updateUserInfo(UpdateUserInfoReqBean(sex = chooseSex)) }, {

            })
        }

    }
}